<!--现货手动交易操作页-->
<template>
  <div class="vt-funlvue">

    <!--操作按钮-买卖-->
    <div class="row">
      <div :class="['action-but', getUpDownBr(actionType, true)]" 
      @click="buyClick">
        <text :class="['font32', getUpDownFont(actionType, true)]">{{T("买入")}}</text>
      </div>
      <div class="width10"></div>
      <div :class="['action-but', getUpDownBr(!actionType, false)]"  
      @click="sellClick">
        <text :class="['font32', getUpDownFont(!actionType, false)]">{{T("卖出")}}</text>
      </div>
    </div>

    <!--功能类型-->
    <div class='frame bk4' @click="functionClick">
      <text class="font28 text1 all">{{T(type)}}</text>
      <LImage class="img-arrow-down" :src="Config.img('trading_triangle_white.png')"></LImage>
    </div>

    <!--价格-->
    <template v-if="type=='限价委托'">
      <VTInput class="frame" v-model="price" :changeValue="pair.baseCoinAmount"
      :selectColor="getUpDownBr(true, actionType)" :placeholder="T('价格')"
      @change="priceChange"  />
    </template>
    <template v-else>
      <div class="frame bg2"><text class="font28 text2 fall">{{T('以当前最优价格交易')}}</text></div>
    </template>

    <!--数量-->
    <VTInput class="frame" v-model="num" :unit="numCoin"
    :selectColor="getUpDownBr(true, actionType)" :placeholder="T('数量')"
    @change="numChange"  />
    <div class="frame-tipe"><text class="font24 text2">{{T('可用')+' '+available+' '+availableCoin}}</text></div> 
    <div class="frame-tipe"><text class="font24 text2 text-line1">{{T('交易额')+' '+payNum+' '+(payNum=='--'?'':availableCoin)}}</text></div>
    <WeexSlideBar class="slide" ref='WeexSlideBar' :color="getUpDownFont(true, actionType)" />

    <!--操作-OK-->
    <div v-if="api" :class="['but-action-ok', Config.upDownBg(actionType)]" @click="okClick">
      <text class="font32 text1" v-if="!Config.isLogin">{{T('登录')}}</text>
      <text class="font32 text1" v-else-if="!api.apiId">{{T('录入API')}}</text>
      <text class="font32 text1" v-else-if="actionType">{{T('买入')}}</text>
      <text class="font32 text1" v-else>{{T('卖出')}}</text>
    </div>
  </div>
</template>


<script>
import jconfig from "@/_js/config"
import jmath from "@/_js/math"
import jmodal from "@/_js/modal"
import jhttps from "@/_js/https"

import jtrading from "./trading"

const weexFunction = weex.requireModule("WeexFunction")
const WeexTrading = weex.requireModule("WeexTrading")
const globalEvent = weex.requireModule('globalEvent');


import I18N from "@/_i18n/i18n";
var T = I18N.t;

import VTInput from './VTInput.vue'
export default {
  components: {
    VTInput
  },

  props:{
    api: Object, //api
    pair: Object, //交易对
    depthCout: { //深度数量
      type: Number,
      default: 8,
    }
  },

  watch: {
    api(val, oldVal) {
      if (val.apiId != oldVal.apiId) {
        jtrading.delectApiRsaStr(false);
        this.initData(true);
      } else {
        this.initData(false);
      }
    },
    pair(val, oldVal) {
      if (val.baseCoin != oldVal.baseCoin ||
          val.counterCoin != oldVal.counterCoin) {
        this.initData(true);
      } else {
        this.initData(false);
      }
    }
  },

  data() {
    return {
      T:T,
      Config:jconfig,
      
      publicKey:'', //加密秘钥
      
      actionType:true, //操作：true买入 false卖出

      //委托类型
      types:['限价委托', '市价委托'],
      typex:{'限价委托':'limit', '市价委托':'market'},
      type: '限价委托',

      price: '', //价格
      available:'0', //余额

      num:'', //数量
      maxNum:'0', //可下单最大数量
      payNum:'--', //交易额
    };
  },

  mounted() {
    jconfig.init(()=>{
      //解决滑条未绘制，无法正常配置属性
      setTimeout(() => {
       this.initData();
       this.viewappear();
      }, 100);
    }, [jconfig.OPT_UP_DOWN]);
  },
  
  computed: {
    //输入数量单位-币
    numCoin() {
      if (this.actionType && this.type == '限价委托') {
        return this.pair.counterCoin;
      }
      return this.actionType ? this.pair.baseCoin : this.pair.counterCoin;
    },

    //可用、交易额单位币
    availableCoin() {
      return this.actionType ? this.pair.baseCoin : this.pair.counterCoin;
    }
  },

  methods: {
    
    /************************************************* 通信*/
    //完全显示
    viewappear() {
      //滑条改变触发
      globalEvent.addEventListener("slideChange",(e)=>{
        this.slideChange(e.ratio);
      });
    },

    //完全隐藏
    viewdisappear() {
      globalEvent.removeEventListener("slideChange")
    },

    /********************************************** 初始化*/
    /** 初始化数据
     * 1、清空数量
     * 2、初始化价格
     * 3、更新可用余额
     * 4、更新最大数量
     * 5、更新滑条
     * 6、更新保证金
     */
    initData(isDelect=true) {
      if (isDelect) {
        this.num = '';
        this.price = this.pair.last;
      }
      this.upAvailable();
      this.upMaxNum();
      this.upSlideBar();
      this.upPayNum();
    },

    /********************************************** https*/
    //https下买卖单
    httpsPalceOrder(rsa){
      
      var amount = this.num;
      var param = {'side':this.actionType ? 'buy' : 'sell', //买卖单
                  'type':this.typex[this.type], //委托类型
                  'amount':amount, //下单数量

                  'apiData':rsa,  //API秘钥
                  'exchangeName':this.api.exchangeName, //交易所
                  'counterCoin':this.pair.counterCoin, //交易币
                  'baseCoin':this.pair.baseCoin, //本币所
      }; 


      //价格
      if(this.type == '限价委托') {
        param['price'] = this.price;
      }
      jhttps.postX("manual/palceOrder",param,true,(data)=>{

        if (data.status == 11505) { 
          jtrading.delectApiRsaStr(false);
          jtrading.gtApiRsaStr(this.api, false, true, (newRsa)=>{
            this.httpsPalceOrder(newRsa);
          });
          return;
        }

        jmodal.hideLoad();
        if(data.status == 200){
          jmodal.toast(T('委托成功'));
          WeexTrading.apiChange(this.api.apiId, this.availableCoin, this.payNum);
          this.initData();
          this.$emit('upOrder');
        } else{

          if (data.status == 11605) {
            jmodal.toast('下单数量不足'+this.pair.minVolume+this.pair.baseCoin+'，或不足'+this.pair.minNumber+this.pair.counterCoin);
          } else {
            jmodal.toast(data.msg);
          }
        }
      });
    },

    /********************************************** 其他*/
    //获取涨跌边框色
    getUpDownBr(isUpDown, bol) {
      return isUpDown ? jconfig.upDownBr(bol, 'udRed-b1', 'udGreen-b1') : 'bk4';
    },

    //获取涨跌文字色
    getUpDownFont(isUpDown, bol) {
      return isUpDown ? jconfig.upDownFont(bol) : 'text2';
    },

    /********************************************** 数据更新*/
    //更新余额
    upAvailable() {
      if(!this.api.apiId) {
        this.available = '0';
        return;
      }

      var num =  '0';
      for (let index = 0; index < this.api.accountAssets.length; index++) {
        var assets = this.api.accountAssets[index];
        if (assets.currency == this.availableCoin) {
          var xs = this.availableCoin==this.pair.baseCoin 
          ? this.pair.baseCoinDecimal 
          : this.pair.counterCoinDecimal;
          num = jmath.xiaoshu(assets.availableReal, xs, 2);
          break;
        }
      }
      this.available = num < 0 ? '0' : num;
    },

    //更新最大数量
    upMaxNum(){

       var maxNum = this.available;
       if (this.actionType && this.type == '限价委托') {
        maxNum = jmath.chu(this.available, this.price, this.pair.counterCoinDecimal, 2);
      }
      this.maxNum = maxNum;
    },

    //更新滑条
    upSlideBar(){
      
      var rightStr = this.maxNum + this.numCoin;
      
      var color = jconfig.upDownBg(this.actionType, '#DB4564', '#00A986');

      var ratio = this.num.length ? jmath.chu(this.num, this.maxNum, 2, 2) : '0';
      ratio = ratio > 1 ? '1' : ratio;

      this.$refs.WeexSlideBar && this.$refs.WeexSlideBar.upSlide({rightStr, color, ratio});
    },
    
    //更新交易额
    upPayNum() {
      
      if (!this.num) {
        this.payNum = '--';
        return;
      }

      var payNum = this.num;
      if (this.actionType && this.type == '限价委托') {
        payNum = jmath.cheng(this.num, this.price, this.pair.baseCoinDecimal, 2);
      }
      this.payNum = payNum;
    },

    /********************************************** 数据联动*/
    /** 价格改变
     * 1、更新最大数
     * 2、更新滑条
     * 3、更新保证金
     */
    priceChange(price){

      this.price = price;
      this.upMaxNum();
      this.upSlideBar();
      this.upPayNum();
    },

    /** 滑条改变
     * 1、计算数量
     * 2、更新保证金
     */
    slideChange(ratio){
      if (this.maxNum == 0) {
        this.num = '';
        return;
      }

      var xs = this.numCoin==this.pair.baseCoin 
      ? this.pair.baseCoinDecimal 
      : this.pair.counterCoinDecimal;
      this.num = jmath.cheng(this.maxNum, ratio, xs, 2);

      this.upPayNum();
    },
    
    /** 数量改变
     * 1、更新滑条
     * 2、更新保证金
     */
    numChange(num){
      this.num = num;
      this.upSlideBar();
      this.upPayNum();
    },
    
    /********************************************** 点击*/
    //买入
    buyClick(){
      if (this.actionType) return;
      this.actionType = true;
      this.initData();
    },

    //卖出
    sellClick(){
      if (!this.actionType) return;
      this.actionType = false;
      this.initData();
    },

    //委托类型
    functionClick(){

      var types = [];
      var typed = {};
      for (let index = 0; index < this.types.length; index++) {
        var value = this.types[index];
        typed[T(value)] = index;
        types.push(T(value));
      }
      jmodal.actionSheet(types, T(this.type), (value)=>{
        if (T(this.type) == value) return;

        var index = typed[value];
        this.type = this.types[index];
        this.initData();
      });
    },

    //确定
    okClick(){
      
      if (jtrading.isFunlvue(this.api)) return;
      
      //价格未填写
      if ((this.type == '限价委托') &&
          this.price.length == 0){
        jmodal.toast('请输入价格');
        return;
      }

      //价格不可为0
      if ((this.type == '限价委托') && this.price == 0){
        jmodal.toast('价格不可为0');
        return;
      }

      //数量未填写
      if (this.num.length == 0) {
        jmodal.toast('请输入数量');
        return;
      }

      //数量为0
      if (this.num == 0) {
        jmodal.toast('数量不可为0');
        return;
      }

      //可用余额不足
      if (Number(this.payNum) > Number(this.available)) {
        jmodal.toast('可用余额不足');
        return;
      }

      jmodal.showLoad();
      jtrading.gtApiRsaStr(this.api, false, true, (rsa)=>{
        this.httpsPalceOrder(rsa);
      });
    },
  }
};

</script>

<style src="@/_css/style.css" ></style>

<style scoped>

.vt-funlvue{
  flex: 1;
  flex-direction: column;
  margin-right: 40px;
}
.action-but{
  flex: 1;
  height:72px;
  justify-content: center;
  align-items: center;
  border-radius:2px;
  border-width:2px;
}
.types {
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-top: 50px;
}
.img-arrow-down {
  width:16px;
  height:12px;
  margin-left: 10px;
}
.market-price{
  height:80px;
  flex-direction: row;
  align-items: center;
  padding: 20px;
  margin-top: 60px;
}
.frame {
  height:80px;
  flex-direction: row;
  align-items: center;
  border-radius:2px;
  border-width: 2px;
  padding: 20px;
  margin-top: 57px;
}
.frame-tipe{
  flex-direction: column;
  justify-content: center;
  margin-top: 10px;
  height: 34px;
}
.slide{
  height:94px;
  margin-top: 60px;
  margin-bottom: 40px;
}

.but-action-ok{
  height:80px;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}
</style>